package org.nifi.processors.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpResponse;
import lombok.experimental.UtilityClass;
import org.nifi.processors.config.DataAccessConst;
import org.nifi.processors.config.DataAccessException;
import org.nifi.processors.model.Res;

import java.util.Map;
import java.util.Objects;

@UtilityClass
public class HttpUtils {


    public Map<String, String> buildFormParam(Object value) {
        Map<String, String> param = MapUtil.newHashMap(true);
        if (Objects.isNull(value)) {
            return param;
        }
        if (value instanceof String) {
            param.put(DataAccessConst.DATA, (String) value);
        } else {
            param.put(DataAccessConst.DATA, JsonUtils.serializeJson(value));
        }
        return param;
    }

    public Res parse(HttpResponse response) {
        if (!response.isOk()) {
            throw new DataAccessException(response.getStatus(), response.body());
        }
        Res res = JsonUtils.deserializeJson(response.body(), Res.class);
        if (Objects.isNull(res)) {
            throw new DataAccessException(1001, "返回对象为空");
        }
        if (!Objects.equals(res.getRetCode(), DataAccessConst.SUCCESS_CODE)) {
            throw new DataAccessException(res.getRetCode(), res.getRetMsg());
        }
        return res;
    }
}
